<template>
	<div class='app-container'>
		<div style="margin-bottom: 12px;">
			<el-button @click="handleShow(true)" type="success" icon="el-icon-plus">新增</el-button>
			<el-button @click="handleDeleteList" type="danger" icon="el-icon-delete">删除</el-button>
		</div>
		<el-table :data="tableData" v-loading="listLoading" element-loading-text="加载中..." border fit highlight-current-row @selection-change="handleSelectionChange" style="width: 100%">
			<el-table-column align="center" type="selection" width="55"></el-table-column>
			<el-table-column label="词组" align="center" min-width="180">
				<template slot-scope="scope">
					<el-tag v-for="(tag, index) in scope.row.tags" :key="tag.wordNum" size="small">{{ tag.wordNum }}</el-tag>
				</template>
			</el-table-column>
			<el-table-column prop="wcenterWord" label="中心词" align="center" min-width="100"></el-table-column>
			<el-table-column label="类型" align="center" min-width="100">
				<template slot-scope="scope">
					{{checkType(scope.row.type)}}
				</template>
			</el-table-column>
			<el-table-column prop="createTime" label="创建时间" align="center" width="160"></el-table-column>
			<el-table-column prop="updateTime" label="更新时间" align="center" width="160"></el-table-column>
			<el-table-column label="操作" align="center" width="120">
				<template slot-scope="scope">
					<el-button size="mini" @click="handleShow(false, scope.row)">编辑</el-button>
				</template>
			</el-table-column>
		</el-table>
		<div class="pagination-container">
			<el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="listQuery.pageNum" :page-sizes="[10,20,30,50]" :page-size="listQuery.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total"></el-pagination>
		</div>
		<el-dialog :title="dialogStatus ? '新增': '编辑'" :visible.sync="dialogFormVisible" :closeOnClickModal='false'>
			<el-form :rules="userFormRules" ref="temp" :model="temp" label-position="left" label-width="65px" style='margin: 24px;'>
				<el-form-item label="中心词" prop="wcenterWord">
	              	<el-select 
	              		filterable
						remote
						reserve-keyword
						:remote-method="remoteMethod"
						:loading="searchloading"
	              		popper-class="select-rule"
	              		no-match-text="暂无信息"
	              		no-data-text="暂无信息"
	              		:default-first-option=true
	              		v-model="temp.wcenterWord" 
	              		clearable
	              		placeholder="请输入选择">
	          		    <el-option v-for="(item, index) in tagOptions" :key="item" :label="item" :value="item"></el-option>
	              	</el-select>
				</el-form-item>
				<el-form-item label="标签组">
					<el-tag :key="tag" v-for="tag in temp.tags" closable :disable-transitions="false" @close="handleClose(tag)">{{ tag }}</el-tag>
					<el-input
					  	class="input-new-tag"
					  	v-if="inputVisible"
					  	v-model="inputValue"
					  	ref="saveTagInput"
					  	size="small"
					  	@keyup.enter.native="handleInputConfirm"
					  	@blur="handleInputConfirm">
					</el-input>
					<el-button v-else class="button-new-tag" size="small" @click="showInput" :disabled='temp.tags.length > 9 ? true: false'>+ New Tag</el-button>
				</el-form-item>
				<el-form-item label="类型">
					<el-select  v-model="temp.type" type="text" placeholder="请选择">
						<el-option
							v-for="item in typeOptions"
							:key="item.value"
							:label="item.label"
							:value="item.value">
						</el-option>
					</el-select>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="dialogFormVisible = false">取消</el-button>
				<el-button type="primary" @click="updateUser">确定</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
	import { similarList, similarDelete, addInfo, updateInfo } from '@/api/word'
	import { listAllInfo } from '@/api/events'
	import pinyin from 'pinyin'

	export default {
		name: 'sanmeLabels',
		created() {
			this.getList()
		},
		methods: {
			handleSelectionChange(val) {
				this.multipleSelection = val.map(e => e.id)
			},
			getList() {
				this.listLoading = true
				similarList(this.listQuery).then(res => {
					this.listLoading = false
					this.tableData = res.Data
					this.total = parseInt(res.total)
				})
			},
			handleSizeChange(val) {
				this.listQuery.pageSize = val
				this.getList()
			},
			handleCurrentChange(val) {
				this.listQuery.pageNum = val
				this.getList()
			},
			handleShow(boo, row) {
				this.dialogStatus = boo
				if(boo){
					this.temp.wcenterWord = ''
					this.temp.tags.length = 0
					this.$set(this.temp, 'type', 0)
				} else {
					this.temp = Object.assign({}, row)
					this.temp.tags = row.tags.map(e => { return e.wordNum })
				}
				this.dialogFormVisible = true
				this.$nextTick(() => {
					this.$refs['temp'].clearValidate()
				})
				if(this.tagList.length == 0) this.getSelectList()
			},
			getSelectList() {
				listAllInfo().then(res => {
					this.tagList = res.Data[0]
				})
			},
			remoteMethod(query) {
			  	if (query !== '') {
				    this.searchloading = true;
				    setTimeout(() => {
				      	this.searchloading = false;
				      	this.tagOptions = this.tagList.filter(item => {
							return item.toLowerCase().indexOf(query.toLowerCase()) > -1;
				      	});
			    	}, 200);
			  	}else{
			    	this.tagOptions = [];
			  	}
			},
			handleDeleteList() {
				if(this.multipleSelection.length === 0){
					this.$message({ type: 'warning', message: '请勾选需要删除的数据' })
				 	return
				}
				this.$confirm('确认删除, 是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					similarDelete({ 'batchIds': this.multipleSelection }).then(() => {
						this.getList()
						this.$notify({ title: '成功', message: '删除成功', type: 'success', duration: 2000 })
					})
				}).catch(() => {
					this.$message({ type: 'info', message: '已取消删除' })
				})
			},
			handleClose(tag) {
		        this.temp.tags.splice(this.temp.tags.indexOf(tag), 1);
	      	},
	      	showInput() {
		        this.inputVisible = true;
		        this.$nextTick(_ => {
		          	this.$refs.saveTagInput.$refs.input.focus();
		        });
	      	},
	      	handleInputConfirm() {
		        let inputValue = this.inputValue;
		        if (inputValue) {
		          	this.temp.tags.push(inputValue);
		        }
		        this.inputVisible = false;
		        this.inputValue = '';
	      	},
	      	updateUser(){
		        this.$refs['temp'].validate(valid => {
		          	if (valid) {
			          	if(this.dialogStatus){
			          		let obj = {
			          			tags: [],
								wcenterWord: this.temp.wcenterWord,
								type:this.temp.type
			          		}
			          		obj.tags = this.temp.tags.map(e => { return {'wordNum': e} })
				            addInfo(obj).then(() => {
				              	this.getList()
	      		              	this.dialogFormVisible = false
		              			this.$notify({ title: '成功', message: "新增成功", type: 'success', duration: 5000 })
				            })
			          	} else {
			          		let obj = Object.assign({}, this.temp)
			          		obj.tags = obj.tags.map(e => { return {'wordNum': e} })
				            updateInfo(obj).then(() => {
				              	this.getList()
	      		              	this.dialogFormVisible = false
		              			this.$notify({ title: '成功', message: "保存成功", type: 'success', duration: 5000 })
				            })
			          	}

		          	}
		        })
			  },
			checkType(data) {
				switch(data) {
					case 0:
						return '个股'
					case 1:
						return '概念'
				}
			}
		},
		data() {
			return {
				multipleSelection: [],
				total: null,
				listLoading: false,
				listQuery: {
					pageNum: 1,
					pageSize: 20
				},
				dialogStatus: false,
				dialogFormVisible: false,
				tagOptions: [],
				searchloading: false,
				tagList: [],  //懒加载中间件
				tableData: [],
				temp: {
					wcenterWord: '',
					tags: []
				},
				inputVisible: false,
        		inputValue: '',
        		userFormRules:{
	         	 	wcenterWord: [
			    		{ required: true, message: '请输入选择', trigger: 'blur'},
			      	]
				},
				typeOptions:[{
					value: 0,
					label: '个股'
					},{
					value: 1,
					label: '概念'
					}],
			}
		}
	}
</script>

<style scoped>
	.el-tag {
		margin-right: 5px;
	}
  	.button-new-tag {
	    /*margin-left: 10px;*/
	    height: 32px;
	    line-height: 30px;
	    padding-top: 0;
	    padding-bottom: 0;
  	}
  	.input-new-tag {
	    width: 90px;
	    margin-left: 10px;
	    vertical-align: bottom;
  	}
</style>